package com.ctl.szmd.szmd.ui.fragment

import android.app.DownloadManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.Toast
import androidx.navigation.fragment.findNavController
import com.blankj.utilcode.util.LogUtils
import com.ctl.lib_common.extensions.singleClick
import com.ctl.szmd.szmd.R
import com.ctl.szmd.szmd.databinding.FragmentMainBinding
import com.ctl.szmd.szmd.ui.base.BaseAppBindingFragment
import com.ctl.szmd.szmd.utils.DownloadUtils
import com.permissionx.guolindev.PermissionX

class MainFragment : BaseAppBindingFragment<FragmentMainBinding>() {

    override fun getLayoutId(): Int {
        return R.layout.fragment_main
    }

    override fun initView() {
        getScreenSize()
        binding.btnWm.singleClick {
            findNavController().navigate(R.id.action_mainFragment_to_feature_wm)
//            launchActivity()
        }
//        val path = Utils.getApp().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath
//        LogUtils.i(path)

        binding.btnDowmload.singleClick {
//            requestPermission.launch(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            PermissionX.init(this).permissions(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request { allGranted, grantedList, deniedList ->
                    if (allGranted) {
                        downloadApk()
                    } else {
                        Toast.makeText(
                            requireActivity(),
                            "These permissions are denied: $deniedList",
                            Toast.LENGTH_LONG
                        )
                            .show()
                    }
                }
        }
    }

    //    private val requestPermission =
//        registerForActivityResult(ActivityResultContracts.RequestPermission()) {
//            if (it) downloadApk()
//        }

    private fun downloadApk() {
        Thread {
            val id = DownloadUtils.downloadAPK(
                "http://mudu.insz.net/ApiAppapk/mddqapp.apk",
                "mddqapp.apk"
            )
            while (DownloadUtils.checkDownloadProgress(id, handler) in 0..99) {
                Thread.sleep(1000)
            }
        }.start()
    }

    private fun getScreenSize() {
        val displayMetrics = requireActivity().resources.displayMetrics
        val widthPixels = displayMetrics.widthPixels// 宽度（PX）
        val heightPixels = displayMetrics.heightPixels// 高度（PX）

        val density = displayMetrics.density// 密度（0.75 / 1.0 / 1.5）
        val densityDpi = displayMetrics.densityDpi// 密度DPI（120 / 160 / 240）
        //屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        //屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        val screenWidth = (widthPixels / density).toInt() //屏幕宽度(dp)
        val screenHeight = (heightPixels / density).toInt() //屏幕高度(dp)
        val a =
            "宽度:" + widthPixels.toString() + " 高度:" + heightPixels.toString() + " 密度:" + density.toString() + " 密度DPI:" + densityDpi
                .toString() + "\r\n屏幕dp宽度：" + screenWidth.toString() + " 屏幕dp高度：" + screenHeight
        binding.txtContent.text = a
    }

    private val handler: Handler = Handler(Looper.getMainLooper()) {
        when (it.what) {
            DownloadManager.STATUS_PENDING -> {
                LogUtils.i("准备下载")
            }
            DownloadManager.STATUS_PAUSED -> {
                LogUtils.i("下载暂停")
            }
            DownloadManager.STATUS_SUCCESSFUL -> {
                LogUtils.i("下载完成")
                val downloadId = it.obj as Long
                DownloadUtils.installApp(DownloadUtils.getDownloadPath(downloadId))
            }
            DownloadManager.STATUS_FAILED -> {
                LogUtils.i("下载失败")
            }
            DownloadManager.STATUS_RUNNING -> {
                val progress = it.obj as Int
                LogUtils.i("正在下载  $progress %")
            }
            else -> {
                LogUtils.i("取消下载")
            }
        }
        false
    }
}